// -*- coding: utf-8 -*- 
/**
 * Project: Java8InActionT
 *
 * @author: yanking
 * Create time: 2022-03-17 23:10
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.WordCounter;

import java.util.Spliterator;
import java.util.function.Consumer;

public class WordCountSpliterator implements Spliterator<Character> {

    private final String string;
    private int currentChar;

    public WordCountSpliterator(String string) {
        this.string = string;
    }

    @Override
    public boolean tryAdvance(Consumer<? super Character> action) {
        // 划分迭代器，一个一个元素的交给action方法进行处理
        action.accept(string.charAt(currentChar++));
        // 如果可以继续迭代则返回真，否则返回假
        return currentChar < string.length();
    }

    @Override
    public Spliterator<Character> trySplit() {
        // 划分迭代器的核心功能，用于实现具体的划分操作，可以通过这个方法生成子换分方法
        int currentSize = string.length() - currentChar;
        if (currentSize < 10) {
            // 设定划分阈值，当当前数据长度小于划分阈值的时候就不继续划分（生成子划分迭代器）
            return null;
        }
        for (int spitPos = currentChar + currentSize / 2; spitPos < string.length();
             spitPos++) {
            if (Character.isWhitespace(string.charAt(spitPos))) {
                Spliterator<Character> spliterator = new WordCountSpliterator(string.substring(currentChar, spitPos));
                currentChar = spitPos;
                return spliterator;
            }

        }
        return null;
    }

    @Override
    public long estimateSize() {
        return string.length() - currentChar;
    }

    @Override
    public int characteristics() {
        return ORDERED + SIZED + SUBSIZED + NONNULL + IMMUTABLE;
    }
}

